package com.mzj.saas.mservice.qiyuesuo.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.redis.RedisService;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.Category;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.request.CategoryListRequest;
import com.qiyuesuo.sdk.v2.response.CategoryListResult;
import com.qiyuesuo.sdk.v2.response.SdkResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 契约锁-业务分类
 * 
 * @author shun
 * @createDate: 2021年6月9日 下午8:21:16
 * @version: 1.0
 *
 */
@Service
public class QiYueSuoBusinessService {

	private Logger logger = LoggerFactory.getLogger(QiYueSuoBusinessService.class);

	@Autowired
	private SdkClient sdkClient;
	@Autowired
	private RedisService redisService;

	/**
	 * 获取第一个业务分类信息
	 * 
	 * @param vo
	 * @return
	 * @author shun
	 * @date 2021年6月9日
	 */
	public Long getCategoryList(Long orgId, String tenantName) {
		// 查询缓存, 如果缓存未找到, 查询接口
		Long categoryId = redisService.getCategoryId(orgId);
		if (categoryId != null) {
			return categoryId;
		}
		try {
			CategoryListRequest request = new CategoryListRequest(0, 1);
			request.setTenantName(tenantName);
			String response = sdkClient.service(request);
			SdkResponse<CategoryListResult> responseObj = JSONUtils.toQysResponse(response, CategoryListResult.class);
			if (responseObj.getCode() == 0) {
				CategoryListResult categoryList = responseObj.getResult();
				logger.info("业务分类列表查询，数量:{}, 分类信息={}", categoryList.getTotalCount(),
						JSON.toJSONString(categoryList.getList().get(0)));

				Category category = categoryList.getList().get(0);
				redisService.putCategoryId(orgId, category.getId());
				return category.getId();
			} else {
				logger.info("业务分类列表失败，错误码:{}，错误信息:{}", responseObj.getCode(), responseObj.getMessage());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		return null;
	}
}